import axios from 'axios';
import { useHistory } from 'react-router-dom';

const instance = axios.create({
  baseURL: '/',
  timeout: 30000,
  headers: {
    'Authorization': localStorage.getItem('userToken') || ''
  }
});

instance.interceptors.response.use(function(response) {
  switch (response.data.code) {
    case 403:
      localStorage.removeItem('userToken');
      const history = useHistory();
      history.push('/login', {});
      return response;
    default:
      return response;
  }
}, function(error) {
  try {
    if (error.toString().includes('403')) {
      localStorage.removeItem('userToken');
      const history = useHistory();
      history.push('/login', {});
    }
  } catch (e) {
  }
  return Promise.reject(error);
});

export default instance;
